import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from "../views/Login";
import Home from "../views/Home";
import store from "../store/index";
import axios from "axios";
import {formatMenu} from "../plugins/initMenus";

Vue.use(VueRouter)

const routes = [

  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
  }

]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

export default router

router.beforeEach((to,from,next)=>{

//  判断用户是否已经登录
  const token=sessionStorage.getItem('token');
  console.log('----------token='+token)
  console.log('---------已登录1store=',store)
  if(token==null){
    if(to.path==='/login'){
      next();
    }else {
      next(`/login?redirect=${to.fullPath}`);
      // next({
      //   path:'/login',
      //   query:{redirect:to.fullPath}
      // })


    }
  }
  else
  {//已经登录

console.log(store)
    //判断vuex中是否存在用户基本信息
    if(!store.state.roles||store.state.roles.length<1){
     // 向后端发送请求
      axios.get('/user/getInfo').then(res=>{
  console.log(res)
      //  得到用户信息
        const user=res.data.data;
  console.log('user的信息',user)
    store.commit('setName',user.name)
        store.commit('setAvatar',user.avatar)
        // const menu=''user.menus
        store.commit('setMenus',user.menus)
        if(user.roles.length>0){
          console.log('开始对角色、菜单、权限赋值')
        //  添加角色，菜单，权限信息
          store.commit('setRoles',user.roles);
          //格式化菜单
          const menuList=formatMenu(user.menus)
          router.addRoutes(menuList)
          store.commit('setMenus',menuList);

          store.commit('setPermission',user.permissions)
        }
      })
    }
    if(to.path==='/login') {
      next('/')
    }else{
      next()
    }
  }
})
